import axios from 'axios'

// 创建axios实例
const service = axios.create({
  // baseURL: 'https://www.jxzysh.cn/web-api/',
  baseURL: 'http://223.84.153.141:8000', // 线上
  // baseURL: 'http://192.168.50.23:8000', // 测试
  timeout: 5000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    if (uni.getStorageSync('token')) {
      config.headers['Authorization'] = uni.getStorageSync('token') || '' // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    config.headers['Content-Type'] = 'application/json'
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    const code = response.status
    if (code < 200 || code > 300) {
      uni.showToast({
        title: response.message,
        icon: 'none',
        duration: 2000
      });
     
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    let code = 0
    try {
      code = error.response.data.status
    } catch (e) {
      if (error.toString().indexOf('Error: timeout') !== -1) {
        uni.showToast({
          title: '网络请求超时',
          icon: 'none',
          duration: 2000
        });
        return Promise.reject(error)
      }
    }
    if (code) {
      if (code === 401) {
        //退出登录
        uni.showToast({
          title: '登录失效',
          icon: 'none',
          duration: 2000
        });
        uni.reLaunch({
					url: '/pages/login'
				});
      } else if (code === 403) {
        // router.push({ path: '/401' })
      } else {
        const errorMsg = error.response.data.message
        if (errorMsg !== undefined) {
          uni.showToast({
            title: errorMsg,
            icon: 'none',
            duration: 2000
          });
        }
      }
    } else {
      uni.showToast({
        title: '接口请求失败',
        icon: 'none',
        duration: 2000
      });
    }
    return Promise.reject(error)
  }
)
export default service
